package com.example.photo.aop;

import com.example.photo.common.ErrorCode;
import com.example.photo.exception.BusinessException;
import com.example.photo.utils.JwtTokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 刷新Token
 *
 * @author Lwh
 * @time 2023/03/27 01:42
 */
@Aspect
@Component
public class TokenRefreshInterceptor {
//    @Around("@annotation(tokenRefresh)")
    @Around("execution(* com.example.photo.controller.*.*(..))")
    public Object doInterceptor(ProceedingJoinPoint joinPoint/*, TokenRefresh tokenRefresh*/) throws Throwable {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) requestAttributes).getResponse();

        String oldToken = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
        if (StringUtils.isBlank(oldToken)) {
            //token为空直接放行
            return joinPoint.proceed();
        }
        if (JwtTokenUtils.isTokenExpired(oldToken)) {
            //token过期则报错
            throw new BusinessException(ErrorCode.NO_AUTH, "Token已过期");
        }
        //token合法则刷新过期时间
        String token = JwtTokenUtils.refreshToken(oldToken);
        assert response != null;
        response.setHeader(JwtTokenUtils.TOKEN_HEADER, token);

        return joinPoint.proceed();
    }
}
